<template>
  <!--  资产立项详情（编辑、查看）-->
  <div>
    <a-card v-if="editMode" :bordered="false" class="card">
        <span>所属项目：</span>
        <orgTreeSelect
            :auto-selected="false"
            style="width: 20vw;display:inline-block"
            is-maintenance
            disabled
            allow-clear
            :isNeedAuth="false"
            :isHasChildren="false"
            :is-show-project-status="true"
            :is-search-page="true"
            :is-query-projec-detail="false"
            :check-strictly="false"
            :placeholder="placeholder"
            :need-tags="[]"
            @select="selectPreOrg"
        ></orgTreeSelect>
    </a-card>
    <searchData
          v-else
          ref="searchCom"
          :search-data="searchData || searchArr"
          :refreshCom="false"
          :isExpand="true"
          :rowCount="4"
          @search="search"/>

    <a-card :bordered="false">
      <b-table
          ref="table"
          class="wrapperTable"
          :showPage="false"
          :out-loading.sync="processing"
          size="default"
          :scroll="{x: 1200, y: 'calc(50vh)' }"
          :selectConfig="{use: true, type: 'checkbox',rowKey: 'index' }"
          :out-selected-row-keys.sync="outSelectedRowKeys"
          :rowKey="record => record.id"
          :columns="tabColumnsImport"
          :request="loadData"
      >
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>


        <template
            slot="assetNature"
            slot-scope="key, record"
        >
          {{ mapAssetNature(key) }}
        </template>
        <ExportExcel
            v-if="!editMode"
            slot="suffix"
            :disabled= "tableData.length===0"
            ref="exportExcel"
            :export-list="exportList"
            icon="export"
            file-name="立项信息明细.xlsx"
            button-text="导出全部"
            :beforeDownload="beforeDownload"
        />
        <a-button
            slot="suffix"
            v-btnPermission="'dc_005_tra_01'"
            v-if="!editMode"
            :disabled="tableData.length === 0 || outSelectedRowKeys.length === 0"
            @click="toTransformPage"
            type="primary">
          转资产
        </a-button>
        <ExcelImportButton
            slot="suffix"
            v-if="editMode"
            ref="importExcel"
            :loading.sync="loadingImport"
            icon="import"
            button-text="导入新增"
            @handleSubmit="_handleImport"
        />

        <a-popconfirm
            v-if="editMode"
            slot="prefix"
            title="确定要删除?" @confirm="() => handleRemove()">

          <a-button
              v-btn-permission="'dc_005_del_02'"
              type="primary"
              :loading="deleteLoading"
              :disabled="outSelectedRowKeys.length === 0">删除
          </a-button>
        </a-popconfirm>

        <span slot="operation" slot-scope="text, record">
                <a v-if="!editMode" @click="toDetail(record,true)">查看</a>
                <span v-if="editMode">
                  <a-divider type="vertical" v-if="false"/>
                  <a  v-btn-permission="'dc_005_edi_02'" @click="toDetail(record,false)">修改</a>
                </span>
        </span>

        <!--  footer-->

        <a-form-model ref="form" :model="form" :rules="rules" class="importCom" slot="footer" layout="inline">
          <a-row type="flex" justify="space-between">
            <a-col span="5">
              <a-form-model-item prop="supplierName" style="width:100%" label="供应商" :labelCol="{style: 'width: 30%'}"
                                 :wrapperCol="{style: 'width: 70%'}">
                <a-input v-model="form.supplierName" placeholder="请输入供应商" :disabled="!editMode"/>
              </a-form-model-item>
            </a-col>
            <a-col span="6">
              <a-form-model-item prop="setUpTime" style="width:100%" label="立项时间" :labelCol="{style: 'width: 30%'}"
                                 :wrapperCol="{style: 'width: 70%'}">
                <a-date-picker v-model="form.setUpTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
                               autocomplete="off"
                               placeholder="请选择" :disabled="!editMode"/>
              </a-form-model-item>
            </a-col>
            <a-col span="10"  push="1">
              <a-form-model-item label="智慧展厅建设方案"
                                 style="width:100%"
                                 prop="schemeFile"
                                 :labelCol="{style: 'width: 24%'}"
                                 :wrapperCol="{style: 'width: 76%'}">
                <l-table count="5"
                         :disabled="!editMode"
                         :upload-arrys.sync="form.schemeFile"
                         :business-code="businessCode"/>
              </a-form-model-item>
            </a-col>
            <a-col span="3" push="1">
              <a-form-model-item>
                <div style="display:flex">
                  <a-button v-if="editMode" type="primary" @click="submit" :loading="loadingSubmit">提交</a-button>
                  <a-button style="margin-left: 10px" @click="cancel">{{ editMode ? '取消' : '关闭' }}</a-button>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </b-table>

    </a-card>
    <EditDrawModal :itemData.sync="itemData" :visible.sync="editModalVisible" :view-mode="viewMode"></EditDrawModal>

  </div>
</template>

<script>
import OrgTreeSelect from '@/components/OrgTreeSelect'
import EditDrawModal from "./EditDrawModal";
import {detail, deleteBatch, batchAddDetail, updateSetUpInfoSelective} from "@/api/material/assets/assetManage";
import AssetMixIn from "../assetMixin";
import debounce from 'lodash/debounce'
import ExportExcel from "@/components/exportExcel/ExportExcel.vue";

export default {
  name: 'AssetDetail',
  components: {ExportExcel, EditDrawModal},
  mixins: [AssetMixIn],
  data() {
    return {
      detail: {},
      processing: false,
      editMode: undefined,
      baseId: undefined,
      searchData: undefined,
      placeholder: '',
      deleteLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: async (parameter) => {
        if (!this.queryParamIsEmpty) {
          return {
            code: 200,
            data: this.searchTableData,
            totalSize: this.searchTableData.length,
          }
        } else {
          this.processing = true
          let res = this.baseId && await detail(this.baseId)
          this.processing = false
          this.detail = res && res.data
          this.form.setUpTime = this.detail?.info?.setUpTime
          this.form.supplierName = this.detail?.info?.supplierName
          this.form.schemeFile = this.detail?.files || []

          this.tableData = this.detail?.list || []
          return {
            code: 200,
            data: this.tableData,
            totalSize: this.tableData.length,
          }
        }
      }
    }
  },
  methods: {
    cancel() {
      this.$multiTab.closeIframe(this.$route.path)
    },
    submit(){
      this.$refs.form.validate((valid) => {
            if (valid) {
              this.updateSetUpInfo({
                supplierName: this.form.supplierName,
                setUpTime: this.form.setUpTime,
                fileList: this.form.schemeFile.map((item) => item.commonId)
              })
            } else {
              this.$message.warning("请填写完所有必填项信息")
            }
       }
      )
    },
    toDetail(item, viewModel = true) {
      if(!viewModel && item && item.assetNature === 3){
        this.$message.warn('已转资产不支持编辑')
        return
      }
      item.orgName = this.detail.info?.projectName
      this.itemData = item
      this.viewMode = viewModel
      this.editModalVisible = true
    },

    handleRemove() {
      this.deleteLoading = true
      deleteBatch(this.outSelectedRowKeys).then((res) => {
        this.deleteLoading = false
        if (res.data === true) {
          this.queryParam = {}
          this.$refs.table.refresh(true)
          this.$message.success('删除成功')
        }
      }).catch((e) => {
        this.deleteLoading = false
      })
    },

    async _handleImport(e) {
      let form = await this.parseExcel(e)
      batchAddDetail(this.baseId, form).then((res) => {
        if (res.code === '0') {
          this.queryParam = {}
          this.$message.success(`导入${res.data}条`)
          this.$refs.table.refresh(true)
        }
      })
    },

    async beforeDownload() {
      let columnsExport = this.$clone(this.tabColumnsImport)
      this.exportList = [
        {
          columns: columnsExport,
          datas: this.tableData.map(item=>{
            item.assetNature = this.mapAssetNature(item.assetNature)
            return item
          })
        }
      ]
    },

    toTransformPage() {
      if((this.form.schemeFile?.length || 0) === 0) {
        this.$message.warn("请先上传建设方案")
        return
      }

      //console.log('info=',this.detail.info)
      let data = this.selectTableData
      let filterData = data.filter((item) => item.assetNature !== 0);
      if (filterData.length > 0) {
        this.$message.warn("只有属性为“可调拨”的设备可以转资产")
        return
      }
      this.$router.push(
          {
            name: 'AssetTransform',
            params: {info: this.detail.info, list: data}
          }
      )
    },

    updateSetUpInfo: debounce(function (param) {
      if (this.baseId) {
        this.loadingSubmit = true
        updateSetUpInfoSelective({id: this.baseId, ...param})
            .then((res)=>{
              this.loadingSubmit = false
            })
      }
    }, 500)
  },
  activated() {
    let isEdit = this.$route.query.isEdit
    this.editMode = +isEdit === 1
    this.baseId = this.$route.query.id || this.baseId
    this.$refs.table.refresh(false)
  },
  computed: {
    selectTableData: function () {
      let target = this.queryParamIsEmpty ? this.tableData : this.searchTableData
      return target.filter((item) => this.outSelectedRowKeys.includes(item.id))
    },
    _searchArr: function () {
      this.searchArr[0].disabled = true
      this.searchArr[0].isHasChildren = false
      this.searchArr[0].placeholder = this.detail.info?.projectName
      return this.searchArr
    }
  },
  watch: {
    'detail.info'(newVal, val) {
      this.placeholder = `${newVal?.branchName}-${newVal?.projectName}`
      this.searchArr[0].placeholder = this.placeholder
      this.searchData = this.$clone(this.searchArr)
      this.searchArr[0].disabled = true
    }
  }
}

</script>


<style scoped lang="less">

.importCom /deep/ .ant-form-item-label {
  text-align: left;
}

.importCom /deep/ .ant-upload-list {
  float: right;
}

.wrapperTable /deep/ .ant-table-tbody > tr > td {
  white-space: nowrap;
  height: 52px !important;
}
/deep/ .card  .treeOrgBox .searchIcon{
  top: 6px;
}
.wrapperTable /deep/ .ant-table-body {
  min-height: 50vh;
}

/deep/ .ant-card-body table{
  margin-left: 0;
  margin-right: 0;
}

/deep/ .ant-table-row .ant-table-row-cell-break-word{
  overflow:hidden;
  text-overflow:ellipsis;//溢出部分用省略号代替
  -webkit-line-clamp:1; //设置文本显示1行，想要几行把1替换掉就行
  display: table-cell !important; //将对象作为弹性伸缩盒子模型显示;

  white-space:nowrap;
  word-break: break-all;
}
/deep/ .ant-table-row-cell-last{
  width: 95px;
}

</style>